package top.lilele.adminSystem.web;

import cn.hutool.system.RuntimeInfo;
import cn.hutool.system.SystemUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import top.lilele.adminSystem.dto.ServerDto;
import top.lilele.adminSystem.utils.BaseResponse;
import top.lilele.adminSystem.utils.ResponseCodeEnum;
import top.lilele.adminSystem.utils.Utils;

/**
 * @author lilele
 */
@RestController
@RequestMapping(value = "server")
public class ServerController {

    @PostMapping(value = "query")
    public BaseResponse query() {
        ServerDto serverDto = new ServerDto();
        RuntimeInfo runtimeInfo = SystemUtil.getRuntimeInfo();
        SystemInfo systemInfo = new SystemInfo();
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        GlobalMemory memory = hardware.getMemory();
        serverDto.setTotalMemory(memory.getTotal());
        serverDto.setTotalMemoryLabel(Utils.formatByte(memory.getTotal()));
        serverDto.setFreeMemory(memory.getAvailable());
        serverDto.setFreeMemoryLabel(Utils.formatByte(memory.getAvailable()));
        serverDto.setUsedMemory(memory.getTotal() - memory.getAvailable());
        serverDto.setUsedMemoryLabel(Utils.formatByte(memory.getTotal() - memory.getAvailable()));
        serverDto.setUsedMemoryPercentage(Double.parseDouble(String.format("%.2f", (double) (memory.getTotal() - memory.getAvailable()) / (double) memory.getTotal() * 100)) + "%");
        serverDto.setTotalJVMMemory(runtimeInfo.getTotalMemory());
        serverDto.setTotalJVMMemoryLabel(Utils.formatByte(runtimeInfo.getTotalMemory()));
        serverDto.setUsedJVMMemory(runtimeInfo.getUsableMemory());
        serverDto.setUsedJVMMemoryLabel(Utils.formatByte(runtimeInfo.getUsableMemory()));
        serverDto.setFreeJVMMemory(runtimeInfo.getFreeMemory());
        serverDto.setFreeJVMMemoryLabel(Utils.formatByte(runtimeInfo.getFreeMemory()));
        return BaseResponse.info(ResponseCodeEnum.Success, serverDto);
    }
}
